﻿using BLL;
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MDMUI.SingleBatch
{
    public partial class SIngleBatchEntry : Form
    {
        private SingleBatchEntryBLL singleBatchEntryBLL = new SingleBatchEntryBLL();
        public SIngleBatchEntry()
        {
            InitializeComponent();
        }

        private void textBox21_TextChanged(object sender, EventArgs e)
        {

        }
        private void label15_Click(object sender, EventArgs e)
        {

        }
        private void label16_Click(object sender, EventArgs e)
        {

        }
        private void label17_Click(object sender, EventArgs e)
        {

        }
        private void label18_Click(object sender, EventArgs e)
        {

        }
        private void label19_Click(object sender, EventArgs e)
        {

        }
        private void label20_Click(object sender, EventArgs e)
        {

        }
        private void label29_Click(object sender, EventArgs e)
        {

        }
        private void label30_Click(object sender, EventArgs e)
        {

        }
        private void label3_Click(object sender, EventArgs e)
        {

        }
        private void label4_Click(object sender, EventArgs e)
        {

        }
        private void SIngleBatchEntry_Load(object sender, EventArgs e)
        {
            //设备表
            EquipmentRepository equipmentRepository = new EquipmentRepository();
            List<Equipment> equipmentData = equipmentRepository.GetAllEquipments();
            try
            {
                // 清空 ComboBox
                equipmentModel.Items.Clear();

                // 遍历设备数据并添加到 ComboBox
                foreach (var equipment in equipmentData)
                {
                    equipmentModel.Items.Add(equipment.EquipmentType);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading equipment models: {ex.Message}");
            }
            //获取工艺包表
            ProcessPackageRepository processPackageRepository = new ProcessPackageRepository();
            List<ProcessPackage> processPackageData = processPackageRepository.GetAllProcessPackages();
            try
            {
                // 清空 ComboBox
                package.Items.Clear();

                // 遍历设备数据并添加到 ComboBox
                foreach (var processPackage in processPackageData)
                {
                    package.Items.Add(processPackage.Name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading equipment models: {ex.Message}");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (int.TryParse(textBox1.Text, out int batchId))
            {
                // 调用 BLL 层的方法获取批次数据
                Batch batchData = singleBatchEntryBLL.showBatchMeg(batchId);
                if (batchData == null)
                {
                    MessageBox.Show("未找到批次数据");
                    return;
                }

                // 获取产品数据
                Product productData = singleBatchEntryBLL.GetProductById(batchData.ProductId);
                if (productData == null)
                {
                    MessageBox.Show("未找到产品数据");
                    return;
                }

                // 获取总流程id
                int totalProcessId = batchData.TotalProcessId;
                TotalProcess totalProcessData = singleBatchEntryBLL.GetTotalProcessById(totalProcessId);
                int stationId = totalProcessData.TotalProcessId;
                Station stationData = singleBatchEntryBLL.GetStationById(stationId);
                int productFlowId = productData.FlowId;
                int productStationId = productData.StationId;
                ProcessFlow FlowData = singleBatchEntryBLL.GetProcessFlowById(productFlowId);
                Station StationData = singleBatchEntryBLL.GetStationById(productStationId);

                // 获取总流程下的所有工站
                List<Station> stationTotolData = singleBatchEntryBLL.GetStationByTotolId(totalProcessId);
                int totalStationCount = stationTotolData.Count;

                // 检查 flowId 和 stationId 是否为总流程长度加 1
                if (productData.FlowId == totalStationCount + 1 && productData.StationId == totalStationCount + 1)
                {
                    MessageBox.Show("该产品已完成所有流程");
                    return; // 不继续执行后续代码
                }

                // 将数据分配给窗体上的控件
                batchType.Text = batchData.BatchType;
                verboseType.Text = "Production";
                quantity.Text = batchData.Quantity.ToString();
                subQuantity.Text = batchData.SubQuantity.ToString();
                unit.Text = batchData.Unit.ToString();
                lockingState.Text = "未锁定";
                productNum.Text = batchData.ProductId.ToString();
                workOrderNum.Text = batchData.WorkOrderId.ToString();
                goodNum.Text = batchData.GoodQuantity.ToString();
                noGoodNum.Text = batchData.NGQuantity.ToString();
                wipStatus.Text = "未锁定";
                repairStatus.Text = "NotOnhold";
                processFlow.Text = FlowData.FlowName;
                versionNum.Text = FlowData.ProcessFlowVersion;
                describe.Text = FlowData.Description;
                scrapQty.Text = "0";
                scrapSubQty.Text = "0";
                processStatus.Text = "Wait";
                reworkStatus.Text = "unRework";
                station.Text = StationData.StationName;
                stationVesion.Text = StationData.StationVersion;
                StationDescription.Text = StationData.StationDescription;
                //载具
                Carrier.Text = batchData.EventRemarks;
            }
            else
            {
                MessageBox.Show("请输入有效的批次数");
            }
        }

        private void verboseType_TextChanged(object sender, EventArgs e)
        {

        }

        private void equipmentModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            //设备表
            EquipmentRepository equipmentRepository = new EquipmentRepository();
            //设备下拉选项
            string selectedEquipmentModel = equipmentModel.SelectedItem?.ToString();
            int equipmentID = singleBatchEntryBLL.GetEquipmentIdByModel(selectedEquipmentModel);
            //int processCapacity = singleBatchEntryBLL.GetProcessCapacityByEquipmentModel(selectedEquipmentModel);
            //程序包下拉选项
            string selectedPackage = package.SelectedItem?.ToString();
            int processPackageId = singleBatchEntryBLL.GetProcessPackageIdByName(selectedPackage);
            //根据程序包id查找程序包数据
            ProcessPackage processPackageData = singleBatchEntryBLL.GetProcessPackageById(processPackageId);
            //获取工艺包表
            //ProcessPackageRepository processPackageRepository = new ProcessPackageRepository();
            //List<ProcessPackage> processPackageData = processPackageRepository.GetAllProcessPackages();
            //总工艺流程表
            Equipment equipmentData = singleBatchEntryBLL.GetEquipmentById(equipmentID);
            //设备说明
            equipmentDescription.Text = equipmentData.EquipmentDescription;
            //设备产品编号
            equipmentProductNum.Text = equipmentData.EquipmentModel;
            //状态
            deviceStatus.Text = equipmentData.EquipmentStatus;
            //锁定状态
            LockStatus.Text = equipmentData.LockStatus;
            //设备类型
            deviceType.Text = "Process";
            //详细类型
            DetailedEquipmentType.Text = equipmentData.DetailedEquipmentType;
           
            //通信状态
            CommunicationStatus.Text = equipmentData.CommunicationStatus;
            //设备号
            equipemtNum.Text = equipmentData.EquipmentId.ToString();
        }

        private void package_SelectedIndexChanged(object sender, EventArgs e)
        {
            //程序包下拉选项
            string selectedPackage = package.SelectedItem?.ToString();
            int processPackageId = singleBatchEntryBLL.GetProcessPackageIdByName(selectedPackage);
            //根据程序包id查找程序包数据
            ProcessPackage processPackageData = singleBatchEntryBLL.GetProcessPackageById(processPackageId);
            //子程序名
            subProgramName.Text = processPackageData.Description;
            //设备程序名
            packageName.Text = processPackageData.Name;
            //批次程序名
            batchPackageName.Text = processPackageData.Name;
        }
        //将设备id,程序包id,产品id,备注，用户添加到批次工站表，修改产品表进出站状态
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                Batch batchData = null; // 声明变量
                if (int.TryParse(textBox1.Text, out int batchId))
                {
                    batchData = singleBatchEntryBLL.showBatchMeg(batchId);
                }
                // 检查 batchData 是否为 null 并且 LockStatus 是否为 “已投产”
                if (batchData == null || batchData.LockStatus != "已投产")
                {
                    MessageBox.Show("批次未投产");
                    return;
                }

                // 获取选中的设备型号
                string selectedEquipmentModel = equipmentModel.SelectedItem?.ToString();
                if (string.IsNullOrEmpty(selectedEquipmentModel))
                {
                    MessageBox.Show("请选择设备型号");
                    return;
                }

                // 获取设备ID
                int equipmentID = singleBatchEntryBLL.GetEquipmentIdByModel(selectedEquipmentModel);
                if (equipmentID == -1)
                {
                    MessageBox.Show("未找到设备ID");
                    return;
                }

                // 获取选中的程序包名称
                string selectedPackage = package.SelectedItem?.ToString();
                if (string.IsNullOrEmpty(selectedPackage))
                {
                    MessageBox.Show("请选择程序包");
                    return;
                }

                // 获取程序包ID
                int processPackageId = singleBatchEntryBLL.GetProcessPackageIdByName(selectedPackage);
                if (processPackageId == -1)
                {
                    MessageBox.Show("未找到程序包ID");
                    return;
                }

                // 获取产品ID
                string productNumText = productNum.Text.Trim();
                if (!int.TryParse(productNumText, out int productId))
                {
                    MessageBox.Show("请输入有效的数字产品ID");
                    return;
                }

                // 更新产品的进出站状态
                int updateResult = singleBatchEntryBLL.UpdateProductEntryAndExitStatus(productId, "已进站"); // 假设更新为 "InStation"

                if (updateResult > 0)
                {
                    MessageBox.Show("产品进出站状态更新成功！");
                }
                else
                {
                    MessageBox.Show("产品进出站状态更新失败！");
                }

                // 获取备注
                string remarks = remark.Text.Trim();

                // 获取用户名
                string userNameText = userName.Text.Trim();
                if (string.IsNullOrEmpty(userNameText))
                {
                    MessageBox.Show("请输入用户名");
                    return;
                }

                // 根据用户名获取用户ID
                int userId = singleBatchEntryBLL.GetUserIdByUsername(userNameText);
                if (userId == -1)
                {
                    MessageBox.Show("未找到用户ID");
                    return;
                }

                // 创建 BatchStation 对象
                BatchStation batchStation = new BatchStation
                {
                    ProductId = productId,
                    ProcessPackageId = processPackageId,
                    UserId = userId,
                    Remark = remarks,
                };

                BatchStationRepository batchStationRepository = new BatchStationRepository();
                // 调用 DAL 层的方法添加数据
                int result = batchStationRepository.AddBatchStation(batchStation);

                if (result > 0)
                {
                    MessageBox.Show("数据添加成功！");
                }
                else
                {
                    MessageBox.Show("数据添加失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }
    }
}
